<template>
  <div class="user-edit">
    <el-form
      :model="editForm"
      ref="editForm"
      label-width="70px"
      :rules="rules"
      style="width: 400px; margin: 10px 14px"
    >
      <el-form-item>
        <div class="insert-avatar">
          <div class="avatar">
            <img :src="editForm.avatar || defaultAvatar" alt="" />
            <el-upload
              action="zhanweifu"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="changeFile"
            >
              <span v-loading="uploadLoading"></span>
            </el-upload>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="登录名">
        <el-input
          disabled
          v-model="editForm.userName"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="userPwd">
        <el-input
          v-model="editForm.userPwd"
          placeholder="请填写密码"
          autocomplete="off"
          :clearable="true"
          @input="changeForm"
        ></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="editForm.name"
          placeholder="请填写姓名"
          autocomplete="off"
          :clearable="true"
          @input="changeForm"
        ></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select
          v-model="editForm.gender"
          autocomplete="off"
          :clearable="true"
          :popper-append-to-body="false"
          style="width: 120px"
          @input="changeForm"
        >
          <el-option label="男" value="1"></el-option>
          <el-option label="女" value="2"></el-option>
          <el-option label="保密" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="editForm.phone"
          placeholder="请填写手机号"
          :clearable="true"
          @input="changeForm"
        ></el-input>
      </el-form-item>
      <el-form-item label="简介">
        <el-input
          type="textarea"
          rows="3"
          v-model="editForm.introduce"
          placeholder="填写个人简介"
          @input="changeForm"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="editForm.status"
          autocomplete="off"
          :clearable="true"
          :popper-append-to-body="false"
          style="width: 120px"
          @input="changeForm"
        >
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          v-show="isShow"
          type="success"
          @click="update"
          :loading="updateLoading"
          >更新</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getUserById, updateUser } from "@/api/admin/user";
import { uploadFile } from "@/api/common";
import defaultAvatar from "@/assets/default.jpg";
export default {
  name: "EditUserView",
  data() {
    return {
      defaultAvatar,
      editForm: {
        userName: "",
        userPwd: "",
        name: "",
        gender: "",
        phone: "",
        avatar: "",
        introduce: "",
        status: "",
      },
      copyForm: {},
      isShow: false,
      uploadLoading: false,
      updateLoading: false,
      rules: {
        userPwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 12,
            message: "长度在 3 到 12 个字符",
            trigger: "blur",
          },
        ],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 11, max: 11, message: "请输入11位手机号", trigger: "blur" },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "请输入正确格式的手机号",
            trigger: "blur",
          },
        ],
        status: { required: true, message: "请选择状态", trigger: "change" },
      },
    };
  },
  props: ["id"],
  created() {
    this.getUserInfo();
  },
  methods: {
    async getUserInfo() {
      const res = await getUserById(this.id);
      this.editForm = Object.assign({}, res.data);
      this.copyForm = Object.assign({}, res.data);
      this.editForm.gender = this.editForm.gender.toString();
      this.editForm.status = this.editForm.status.toString();
      this.copyForm.gender = this.copyForm.gender.toString();
      this.copyForm.status = this.copyForm.status.toString();
      this.copyForm.introduce = this.editForm.introduce;
    },
    // 检测表单数据是否修改
    changeForm() {
      const objectEqual =
        JSON.stringify(this.editForm) === JSON.stringify(this.copyForm);
      if (!objectEqual) {
        this.isShow = true;
      } else {
        this.isShow = false;
      }
    },
    // 更新用户信息
    update() {
      this.$refs.editForm.validate(async (v) => {
        if (v) {
          try {
            this.updateLoading = true;
            const res = await updateUser(this.editForm);
            this.$router.push({
              name: "AdminUserManage",
            });
          } finally {
            this.updateLoading = false;
          }
        }
      });
    },
    // 选择文件，上传头像
    async changeFile(file) {
      // 判断格式是否正确
      const bool = this.verifyFormat(file);
      if (!bool) {
        return;
      }
      // 上传到服务器
      // console.log("上传到服务器,返回图片路径赋值给insertForm.cover");
      this.uploadLoading = true;
      try {
        let formData = new FormData();
        // 拿到存在file中的文件存放到formData中
        formData.append("file", file.raw);
        const res = await uploadFile(formData);
        this.editForm.avatar = res.data;
        this.changeForm();
      } finally {
        this.uploadLoading = false;
      }
    },
    // 上传头像前校验格式
    verifyFormat(file) {
      const isJPG =
        file.raw.type === "image/jpeg" || file.raw.type === "image/png";
      const isLt2M = file.raw.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 jpg/jpeg/png 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style lang="less" scoped>
.user-edit {
  width: 100%;
  height: 100%;
  .insert-avatar {
    position: relative;
    width: 100%;
    height: 70px;
    .avatar {
      width: 100px;
      height: 100px;
      position: relative;
      top: 50%;
      left: 44%;
      transform: translate(-50%, -50%);
      border-radius: 50%;
      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        cursor: pointer;
      }
      span {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 100px;
        height: 100px;
        border-radius: 50%;
        transform: translate(-50%, -50%);
        &::before {
          content: "上传头像";
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          width: 100px;
          height: 100px;
          background-color: rgba(0, 0, 0, 0.16);
          text-align: center;
          line-height: 100px;
          border-radius: 50%;
          cursor: pointer;
          opacity: 0;
          visibility: hidden;
          z-index: 1;
          color: black;
        }
        &:hover::before {
          opacity: 1;
          visibility: visible;
        }
      }
    }
  }
}
// 解决下拉框显示不完整问题
/deep/.el-select-dropdown__wrap.el-scrollbar__wrap {
  margin-bottom: 0 !important;
}
</style>